package com.shiningstars.service;

import java.util.Date;

import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;

import com.shiningstars.database.DatabaseHandler;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Utilities;
import com.shiningstars.tools.ExceptionHandler;
import com.shiningstars.tools.MailSender;
import com.shiningstars.valuebeans.Error;

public class ErrorService extends Service implements Constants, Config {

	int attempts = SERVICE_ATTEMPTS;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

		final DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());

		new Thread() {
			@Override
			public void run() {

				Looper.prepare();

				while (attempts > 0) {
					attempts--;
					while (true) {
						Error error = databaseHandler.getError();

						if (null != error) {
							try {
								MailSender sender = new MailSender("ssp.app.mailer@gmail.com", "ssp@2014");
								MimeMessage message = sender.sendMail(
										"SSP Error",
										"Mobile Number : " + error.getMobileNumber() + "\nIMEI Number : "
												+ error.getImeiNumber() + "\nError Time : " + new Date(error.getDate())
												+ "\nTag : " + error.getTag() + "\n\n" + error.getDescription(),
										"mailer@shiningstarspathshala.com", "saurabh.dedhia.ssp@gmail.com");
								Transport.send(message);

								databaseHandler.deleteError(error.getId());
							} catch (Exception e) {
								e.printStackTrace();
								break;
							}
						} else {
							break;
						}
					}

					try {
						Thread.sleep(SERVICE_THREAD_SLEEP);
					} catch (InterruptedException e) {
						Utilities.logError(getApplicationContext(), ErrorService.class.getName(), e);
						break;
					}
				}

				stopService(new Intent(getApplicationContext(), ErrorService.class));

				Looper.loop();
				Looper.myLooper().quit();
			}
		}.start();

		return START_NOT_STICKY;
	}
}